package com.party.business.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.party.business.FieldReflectionUtil;
import com.party.business.domain.*;
import com.party.business.service.*;
import com.party.business.service.impl.KcTypeServiceImpl;
import com.party.common.annotation.Log;
import com.party.common.annotation.RepeatSubmit;
import com.party.common.config.RuoYiConfig;
import com.party.common.constant.Constants;
import com.party.common.core.controller.BaseController;
import com.party.common.core.domain.AjaxResult;
import com.party.common.core.domain.entity.SysDept;
import com.party.common.core.domain.entity.SysDictData;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.core.domain.model.LoginUser;
import com.party.common.core.domain.model.RegisterBody;
import com.party.common.core.page.TableDataInfo;
import com.party.common.enums.BusinessType;
import com.party.common.exception.ServiceException;
import com.party.common.utils.*;
import com.party.common.utils.file.FileUtils;
import com.party.common.utils.poi.ExcelUtil;
import com.party.system.domain.SysConfig;
import com.party.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.rmi.ServerException;
import java.rmi.server.ExportException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 网站接口
 */
@RestController
@RequestMapping("/webApi")
public class TWebApiController extends BaseController {
//
    @Autowired
    private ITLbImageService tLbImageService;
//
//
//    @Autowired
//    private ITNoticeService tNoticeService;
//
//
//    @Autowired
//    private ITNewsService tNewsService;
//
//
//    @Autowired
//    private ISysUserService sysUserService;
//
//    @Autowired
//    private ITFjFileService tFjFileService;
//
    @Autowired
    private ISysUserService sysUserService;
//
//
    @Autowired
    private IKcTypeService kcTypeService;
//
//
    @Autowired
    private ITTwxxService tTwxxService;
//


    @Autowired
    private IZqTypeService zqTypeService;


    @Autowired
    private IKcService kcService;

//
//    /**
//     * 注册协议和隐私政策  关于我们
//     */
//    @GetMapping("/nologin/twxxlist")
//    public   AjaxResult twxxlist(TTwxx tTwxx) {
//        List<TTwxx> list = tTwxxService.selectTTwxxList(tTwxx);
//        return AjaxResult.success(list);
//    }



    @Autowired
    private ITSyNrService tSyNrService;



    /**
     * 首页业务指南内容
     */
    @GetMapping("/nologin/getSyNr")
    public  AjaxResult  getSyNr(TSyNr vo) {
        List<TSyNr> tSyNrs = tSyNrService.selectTSyNrList(vo);
        return AjaxResult.success(tSyNrs);
    }

    /**
     * 轮播图列表
     */
    @GetMapping("/nologin/getLbImageList")
    public  AjaxResult getLbImageList(TLbImage tLbImage) {
        List<TLbImage> list = tLbImageService.selectTLbImageList(tLbImage);
        return AjaxResult.success(list);
    }


    //

//    /**
//     * 用户个人信息
//     */
//    @GetMapping("/getUserInfo")
//    public AjaxResult getInfo() {
//        Long userId = SecurityUtils.getUserId();
//        SysUser sysUser = sysUserService.selectUserByIdApp(userId);
//        return AjaxResult.success(sysUser);
//    }


//
//
    @Autowired
    private ISysConfigService configService;
//
    /**
     * 客服电话   客服微信号
     */
    @GetMapping("/nologin/getxtpzList")
    public   AjaxResult getxtpzList() {
        SysConfig sysConfig = new SysConfig();
        List<SysConfig> sysConfigs = configService.selectConfigList(sysConfig);
        return AjaxResult.success(sysConfigs);
    }


    @Autowired
    private ITArticleTypeService tArticleTypeService;


    /**
     * 文章类型列表
     */
    @GetMapping("/nologin/articleTypeList")
    public  AjaxResult articleTypeList(TArticleType tArticleType) {
        List<TArticleType> list = tArticleTypeService.selectTArticleTypeList(tArticleType);
        return AjaxResult.success(list);
    }

    @Autowired
    private ITArticleService tArticleService;

    /**
     * 文章列表(分页)
     */
    @GetMapping("/nologin/tArticleList" )
    public  TableDataInfo   tArticleList(TArticle tArticle) {
        startPage();
        if("1".equals(tArticle.getSelectType())){
            tArticle.setTitle(tArticle.getTitle());
        }else{
            tArticle.setContent(tArticle.getTitle());
        }
        List<TArticle> list = tArticleService.selectTArticleList(tArticle);
        return getDataTable(list);
    }
    /**
     * 相关视频--传入视频文章id
     */
    @GetMapping("/nologin/tArticleListXgVideo" )
    public  AjaxResult   tArticleListXgVideo(TArticle tArticle) {
        TArticle tArticledetail = tArticleService.getById(tArticle.getId());
        String flType = tArticledetail.getFlType();
        String mkType = tArticledetail.getMkType();
        // 查询相同flType的数据
        QueryWrapper<TArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fl_type",flType);
        queryWrapper.ne("id",tArticle.getId());
        queryWrapper.eq("mk_type",mkType);
        // 视频类型
        queryWrapper.eq("dmt_type","2");
        queryWrapper.orderByDesc("pub_date");
        // 查询3条
        queryWrapper.last("limit 3");
        List<TArticle> list = tArticleService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    /**
     * 文章详情
     */
    @GetMapping(value = "/nologin/articleDetail/{id}" )
    public AjaxResult articleDetail(@PathVariable("id" ) String id) {
        TArticle byId = tArticleService.getById(id);
        byId.setViewNum(byId.getViewNum()+1);
        tArticleService.updateById(byId);
        return AjaxResult.success(byId);
    }


    @Autowired
    private ITCountryTypeService tCountryTypeService;

    /**
     * 国家列表
     */
    @GetMapping("/nologin/countryTypelist")
    public  AjaxResult countryTypelist(TCountryType tCountryType) {
        List<TCountryType> list = tCountryTypeService.selectTCountryTypeList(tCountryType);
        return AjaxResult.success(list);
    }


    @Autowired
    private ITArticleCpTypeService tArticleCpTypeService;

    /**
     * 查询产品分类列表
     */
    @GetMapping("/nologin/tArticleCpTypeList")
    public AjaxResult   tArticleCpTypeList(TArticleCpType tArticleCpType) {
        List<TArticleCpType> list = tArticleCpTypeService.selectTArticleCpTypeList(tArticleCpType);
        return AjaxResult.success(list);
    }


    @Autowired
    private ITNdArticleService tNdArticleService;


    /**
    *
    * 年度十大动态列表
    */
    @GetMapping("/nologin/getNdArticleList")
    public AjaxResult getNdArticleList(TNdArticle tNdArticle) {
        //根据 year的格式为 2024 查询三年内的数据
        QueryWrapper<TNdArticle>  queryWrapper =new QueryWrapper<>();
        queryWrapper.apply("CAST(`year` AS UNSIGNED) >= YEAR(CURDATE()) - 3");
        queryWrapper.orderByDesc("year");
        List<TNdArticle> list = tNdArticleService.list(queryWrapper);
        return AjaxResult.success(list);
    }


    /**
     *
     * 安全动态中间区域
     */
    @GetMapping("/nologin/getAnQdtContent")
    public AjaxResult   getAnQdtContent() {
        TArticleType cpType =new TArticleType();
        cpType.setWzType("1");
        List<TArticleType> tArticleTypes = tArticleTypeService.selectTArticleTypeList(cpType);
        for (int i = 0; i < tArticleTypes.size(); i++) {
            TArticleType tArticleType = tArticleTypes.get(i);
            TArticle  article =new TArticle();
            article.setFlType(tArticleType.getId());
            List<TArticle> list = tArticleService.selectTArticleList(article);
            tArticleTypes.get(i).setArticleList(list);
        }
        return AjaxResult.success(tArticleTypes);
    }

    @Autowired
    private ITTgRecordService tTgRecordService;





    /**
     *
     * 保存投稿信息
     */
    @RepeatSubmit
    @PostMapping("/nologin/saveTgRecord")
    public AjaxResult saveTgRecord(@Validated @RequestBody TTgRecord tTgRecord) {
        return toAjax(tTgRecordService.save(tTgRecord));
    }


    @Autowired
    private ITTgTxService tTgTxService;

    /**
     * 查询投稿要求对象
     */
    @GetMapping("/nologin/getTTgTx" )
    public AjaxResult getTTgTx(TTgTx tTgTx) {
        PageUtils.startPage(1,1);
        List<TTgTx> list = tTgTxService.selectTTgTxList(tTgTx);
        if(!CollectionUtils.isEmpty(list)){
         return    AjaxResult.success(list.get(0));
        }else{
            return  null;
        }
    }



    /**
     * 下载文件
     *
     */
    @GetMapping("/nologin/download")
    public void fileDownload(String fileName, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getProfile();
            String downloadPath = filePath + StringUtils.substringAfter(fileName, Constants.RESOURCE_PREFIX);
            System.out.println(downloadPath);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());

        }
        catch (Exception e)
        {

        }
    }













//

//
//

//
//
//    @Autowired
//    private ITKcService tKcService;
//
//
//    /**
//     * 课程列表
//     */
//    @GetMapping("/getKcList")
//    public TableDataInfo getKcList(TKc kc) {
//        startPage();
//        List<TKc> tKcs = tKcService.selectTKcListApp(kc);
//        return getDataTable(tKcs);
//    }
//
//
//    /**
//     * 课程详情
//     */
//    @GetMapping(value = "/getkcDetail/{id}")
//    public AjaxResult getkcDetail(@PathVariable("id") String id) {
//        return AjaxResult.success(tKcService.selectTKcById(id));
//    }
//







//
//    /**
//     * 用户个人信息--修改
//     */
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
//    @PutMapping("updateUser")
//    public AjaxResult updateUser(@RequestBody SysUser user) {
//        user.setUpdateBy(getUsername());
//        user.setUserId(SecurityUtils.getUserId());
//        return toAjax(sysUserService.updateUserApp(user));
//    }
//
//    /**
//     * 用户个人信息--用户注销
//     */
//    @DeleteMapping("/removeUser")
//    public AjaxResult removeUser() {
//        String username = SecurityUtils.getUsername();
//        if ("admin".equals(username)) {
//            return AjaxResult.error("超级管理员不能注销");
//        }
//        Long[] userIds = {SecurityUtils.getUserId()};
//        return toAjax(userService.deleteUserAppByIds(userIds));
//    }



    @Autowired
    private ITDbService tDbService;

    /**
     * 查询数据表列表(分页)
     */
    @GetMapping("/nologin/getDblist")
    public TableDataInfo getDblist(TDb tDb) {
        startPage();
        List<TDb> list = tDbService.selectTDbListApp(tDb);
        return getDataTable(list);
    }

    /**
     * 查询数据库表详情接口
     */
    @GetMapping(value = "/nologin/getDbDetail/{id}")
    public AjaxResult getDbDetail(@PathVariable("id") String id) {
        return AjaxResult.success(tDbService.getById(id));
    }


    @Autowired
    private ITDbColumnService tDbColumnService;


    /**
     * 查询数据表字段
     */
    @GetMapping("/nologin/getDbColumList")
    public  AjaxResult getDbColumList(TDbColumn tDbColumn) {
        List<TDbColumn> list = tDbColumnService.selectTDbColumnList(tDbColumn);
        return AjaxResult.success(list);
    }
    @Autowired
    private  IFieldShowService fieldShowService;


    /**
     * 插入武器平台
     */
    @GetMapping("/nologin/insertCum")
    public  AjaxResult  insertCum() throws ClassNotFoundException {
//        Class<?> clazz = Class.forName("com.party.business.domain.WeaponPlatform");
//        FieldReflectionUtil util = new FieldReflectionUtil(fieldShowService);
//        util.insertFieldsToDatabase(clazz, "3");

//        Class<?> clazz = Class.forName("com.party.business.domain.ActingData");
//        FieldReflectionUtil util = new FieldReflectionUtil(fieldShowService);
//        util.insertFieldsToDatabase(clazz, "4");

//        Class<?> clazz2 = Class.forName("com.party.business.domain.ExamplesWar");
//        FieldReflectionUtil util2 = new FieldReflectionUtil(fieldShowService);
//        util2.insertFieldsToDatabase(clazz2, "5");

//        Class<?> clazz2 = Class.forName("com.party.business.domain.StrategicPolicie");
//        FieldReflectionUtil util2 = new FieldReflectionUtil(fieldShowService);
//        util2.insertFieldsToDatabase(clazz2, "6");

//        Class<?> clazz2 = Class.forName("com.party.business.domain.CombatPower");
//        FieldReflectionUtil util2 = new FieldReflectionUtil(fieldShowService);
//        util2.insertFieldsToDatabase(clazz2, "7");
//
//        Class<?> clazz2 = Class.forName("com.party.business.domain.ResearchSubmissions");
//        FieldReflectionUtil util2 = new FieldReflectionUtil(fieldShowService);
//        util2.insertFieldsToDatabase(clazz2, "8");

//        Class<?> clazz2 = Class.forName("com.party.business.domain.WeaponsEquipment");
//        FieldReflectionUtil util2 = new FieldReflectionUtil(fieldShowService);
//        util2.insertFieldsToDatabase(clazz2, "9");

        Class<?> clazz2 = Class.forName("com.party.business.domain.PowerbuildOrg");
        FieldReflectionUtil util2 = new FieldReflectionUtil(fieldShowService);
        util2.insertFieldsToDatabase(clazz2, "10");


        return AjaxResult.success();

    }



    @Autowired
    private ISecurityIncidentsService securityIncidentsService;


    @Autowired
    private ITheoreticalDoctrineService theoreticalDoctrineService;



    @Autowired
    private IWeaponPlatformService weaponPlatformService;


    @Autowired
    private IActingDataService actingDataService;


    @Autowired
    private IExamplesWarService examplesWarService;


    @Autowired
    private IStrategicPolicieService strategicPolicieService;

    @Autowired
    private ICombatPowerService combatPowerService;

    @Autowired
    private IResearchSubmissionsService researchSubmissionsService;

    @Autowired
    private IPowerbuildOrgService powerbuildOrgService;

    @Autowired
    private IWeaponsEquipmentService weaponsEquipmentService;



    /**
     * 数据表数据详情
     */
    @GetMapping("/nologin/getTableData")
    public   AjaxResult  getTableData(String id,String type) {
        if("1".equals(type)){
            SecurityIncidents securityIncidents = securityIncidentsService.selectSecurityIncidentsById(id);
            return AjaxResult.success(securityIncidents);
        }else if("2".equals(type)){
            TheoreticalDoctrine theoreticalDoctrine = theoreticalDoctrineService.selectTheoreticalDoctrineById(Long.valueOf(id));
            return AjaxResult.success(theoreticalDoctrine);
        }else if("3".equals(type)){
            WeaponPlatform weaponPlatform = weaponPlatformService.selectWeaponPlatformById(Long.valueOf(id));
            return AjaxResult.success(weaponPlatform);
        }else if("4".equals(type)){
            ActingData actingData = actingDataService.selectActingDataById(Long.valueOf(id));
            return AjaxResult.success(actingData);
        }else if("5".equals(type)){
            ExamplesWar examplesWar = examplesWarService.selectExamplesWarById(Long.valueOf(id));
            return AjaxResult.success(examplesWar);
        }else if("6".equals(type)){
            StrategicPolicie strategicPolicie = strategicPolicieService.selectStrategicPolicieById(Long.valueOf(id));
            return AjaxResult.success(strategicPolicie);
        }else if("7".equals(type)) {
            CombatPower combatPower = combatPowerService.selectCombatPowerById(Long.valueOf(id));
            return AjaxResult.success(combatPower);
        }else if("8".equals(type)){
            ResearchSubmissions researchSubmissions = researchSubmissionsService.selectResearchSubmissionsById(Long.valueOf(id));
            return AjaxResult.success(researchSubmissions);
        }else if("9".equals(type)){
            WeaponsEquipment weaponsEquipment = weaponsEquipmentService.selectWeaponsEquipmentById(Long.valueOf(id));
            return AjaxResult.success(weaponsEquipment);
        }else if("10".equals(type)){
            PowerbuildOrg powerbuildOrg = powerbuildOrgService.selectPowerbuildOrgById(Long.valueOf(id));
            return AjaxResult.success(powerbuildOrg);
        }else {
            return AjaxResult.error();
        }
    }
    /**
     * 数据表数据---分页
     */
    @GetMapping("/nologin/getTableDataList")
    public   TableDataInfo  getTableDataList(String type,String  selectType,String  title) {
        startPage();
        if("1".equals(type)){
            SecurityIncidents  query = new SecurityIncidents();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 事件过程
                query.setIncidentProcess(title);
            }
            List<SecurityIncidents> securityIncidentsList = securityIncidentsService.selectSecurityIncidentsList(query);
            return getDataTable(securityIncidentsList);
        }else if("2".equals(type)){
            TheoreticalDoctrine  query = new TheoreticalDoctrine();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 摘要
                query.setSummary(title);
            }
            List<TheoreticalDoctrine> theoreticalDoctrineList = theoreticalDoctrineService.selectTheoreticalDoctrineList(query);
            return getDataTable(theoreticalDoctrineList);
        }else if("3".equals(type)){
            WeaponPlatform  query = new WeaponPlatform();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                //  定义
                query.setDefinition(title);
            }
            List<WeaponPlatform> weaponPlatformList = weaponPlatformService.selectWeaponPlatformList(query);
            return getDataTable(weaponPlatformList);
        }else if("4".equals(type)){
            ActingData  query = new ActingData();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 演习目的
                query.setPurposeOfExercise(title);
            }
            List<ActingData> actingDataList = actingDataService.selectActingDataList(query);
            return getDataTable(actingDataList);
        }else if("5".equals(type)){
            ExamplesWar  query = new ExamplesWar();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 内容
                query.setContent(title);
            }
            List<ExamplesWar> examplesWarList = examplesWarService.selectExamplesWarList(query);
            return getDataTable(examplesWarList);
        }else if("6".equals(type)){
            StrategicPolicie  query = new StrategicPolicie();
            if("1".equals(selectType)){
                query.setChineseTitle(title);
            }else if("2".equals(selectType)){
                //摘要
                query.setSummary(title);
            }
            List<StrategicPolicie> strategicPolicieList = strategicPolicieService.selectStrategicPolicieList(query);
            return getDataTable(strategicPolicieList);
        }else if("7".equals(type)){
            CombatPower  query = new CombatPower();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 主要职能
                query.setMainDuties(title);
            }
            List<CombatPower> combatPowerList = combatPowerService.selectCombatPowerList(query);
            return getDataTable(combatPowerList);
        }else if("8".equals(type)){
            ResearchSubmissions  query = new ResearchSubmissions();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 定义
                query.setDefinition(title);
            }
            List<ResearchSubmissions> researchSubmissionsList = researchSubmissionsService.selectResearchSubmissionsList(query);
            return getDataTable(researchSubmissionsList);
        }else if("9".equals(type)){
            WeaponsEquipment  query = new WeaponsEquipment();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 概述
                query.setOverview(title);
            }
            List<WeaponsEquipment> weaponsEquipmentList = weaponsEquipmentService.selectWeaponsEquipmentList(query);
            return getDataTable(weaponsEquipmentList);
        }else if("10".equals(type)){
            PowerbuildOrg  query = new PowerbuildOrg();
            if("1".equals(selectType)){
                query.setChineseName(title);
            }else if("2".equals(selectType)){
                // 主要职能
                query.setMainFunctions(title);
            }
            List<PowerbuildOrg> powerbuildOrgList = powerbuildOrgService.selectPowerbuildOrgList(query);
            return getDataTable(powerbuildOrgList);
        }else {
            return null;
        }
    }

    /**
     * 数据表---字段显示控制
     */
    @GetMapping("/nologin/filedSHow")
    public   AjaxResult  filedSHow(FieldShow show){
        List<FieldShow> fieldShows = fieldShowService.selectFieldShowList(show);
        return  AjaxResult.success(fieldShows);
    }


    @Autowired
    private ITFjFileService tFjFileService;

    /**
     * 查询附件文件列表
     */
    @GetMapping("/nologin/fjlist")
    public AjaxResult fjlist(TFjFile tFjFile) {
        List<TFjFile> list = tFjFileService.selectTFjFileList(tFjFile);
        return AjaxResult.success(list);
    }


}
